import axios from 'axios'
import { getToken } from '@/utils/auth'
import { MessageBox, Message } from 'element-ui'
import router from '@/router'
import store from '@/store'
// import Cookies from 'js-cookie'
// create an axios instance
const service = axios.create({
  // baseURL: 'http://127.0.0.1:7001', // url = base url + request url
  timeout: 5000 // request timeout
})
// request interceptor
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use((response)=>{
   const res = response.data
    if (res.code === -2) {
      return Promise.resolve(res)
    }
    if (res.code != 200 && res.code != 1) {
      if (res.code === 401 || res.code === 402 || res.code === 402) {
        MessageBox.confirm(
          '登录状态已过期，您可以继续留在该页面，或者重新登录',
          '系统提示',
          {
            confirmButtonText: '重新登录',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          router.push({ path: '/login' })
          store.dispatch('user/resetToken')
        })
      } else {
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return response
    }
  return response
},(error)=>{
  return Promise.reject(error);
})

export default service
